package com.tarena.luban.demo.gateway.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.function.Supplier;

/*@Component*/
public class MyFilter01 implements GlobalFilter, Ordered {
    //过滤器核心方法

    /**
     * @param exchange webflux底层封装的一个reactive容器对象 包含了请求和响应
     * @param chain 过滤链,贯穿了web容器的一个过滤器集合的.从一个过滤器传入到另一个过滤器
     * @return webflux框架的一个返回结果.
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("myfilter01 经过");
        //拿到请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取相关请求的所有数据
        //1.请求路径 第一种 uri拼接的路径 第二种 path
        URI uri = request.getURI();
        RequestPath path = request.getPath();
        System.out.println("当前请求uri:"+uri);
        System.out.println("当前请求path:"+path);
        //2.请求方法 GET POST PUT DELETE OPTION HEAD
        HttpMethod method = request.getMethod();
        System.out.println("当前请求method:"+method);
        //3.请求参数 localhost:30000/doc.html?name=王翠花&name=刘首付&age=18
        //name={"王翠花","刘首付"} age={"18"}
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        List<String> values = queryParams.get("name");
        System.out.println("当前参数name的值:"+values);
        //4.请求头获取
        HttpHeaders headers = request.getHeaders();
        List<String> headerValues = headers.get("user-agent");
        System.out.println("当前user-agent头的size:"+headerValues.size()+"值:"+headerValues);
        //5.其它 都是通过get方法获取
        InetSocketAddress remoteAddress = request.getRemoteAddress();//客户端ip地址
        System.out.println("当前请求客户端ip:"+remoteAddress.getAddress());
        System.out.println("当前请求客户端ip:"+remoteAddress.getHostName());
        Mono<Void> mono = chain.filter(exchange);
        //控制响应对象response
        //1.拿到响应
        ServerHttpResponse response = exchange.getResponse();
        //2.可以读取当前响应数据 比如头
        HttpHeaders headersResponse = response.getHeaders();
        //3.写出有中文 注意乱码问题 applicaiton/json;charset-utf-8
        headersResponse.setContentType(MediaType.APPLICATION_JSON);
        //4.准备一个输出字符串
        String resultJson="{\"code\":500,\"message\":\"你的请求被拦截了\"}";
        //5.将字符串包装到响应中 从这个过滤器输出响应
        //5.1 从响应中拿到转化的一个数据缓存对象 用这个对象包装一些字符串 二进制
        DataBufferFactory dataBufferFactory = response.bufferFactory();
        //5.2使用缓存数据流对象 将字符串 二进制包装
        DataBuffer wrap =
                dataBufferFactory.wrap(resultJson.getBytes(StandardCharsets.UTF_8));
        //5.3创建一个mono对象,可以接收dataBuffer
        Mono<DataBuffer> writeData=Mono.fromSupplier(new Supplier<DataBuffer>() {
            @Override
            public DataBuffer get() {
                return wrap;
            }
        });
        //5.4使用response输出返回值
        return response.writeWith(writeData);
    }

    @Override
    public int getOrder() {
        return 10;
    }
}









